// utils/audioManager.js
// 音频管理工具类

class AudioManager {
  constructor() {
    this.recorderManager = null;
    this.audioContext = null;
    this.isRecording = false;
    this.isPlaying = false;
    this.recordTimer = null;
    this.recordTime = 0;
  }

  // 初始化录音管理器
  initRecorder(callbacks = {}) {
    this.recorderManager = wx.getRecorderManager();
    
    this.recorderManager.onStart(() => {
      console.log('录音开始');
      this.isRecording = true;
      this.startRecordTimer();
      callbacks.onStart && callbacks.onStart();
    });

    this.recorderManager.onStop((res) => {
      console.log('录音结束', res);
      this.isRecording = false;
      this.stopRecordTimer();
      callbacks.onStop && callbacks.onStop(res);
    });

    this.recorderManager.onError((err) => {
      console.error('录音错误', err);
      this.isRecording = false;
      this.stopRecordTimer();
      callbacks.onError && callbacks.onError(err);
    });
  }

  // 初始化音频播放器
  initPlayer(callbacks = {}) {
    this.audioContext = wx.createInnerAudioContext();
    
    this.audioContext.onPlay(() => {
      this.isPlaying = true;
      callbacks.onPlay && callbacks.onPlay();
    });

    this.audioContext.onEnded(() => {
      this.isPlaying = false;
      callbacks.onEnded && callbacks.onEnded();
    });

    this.audioContext.onError((err) => {
      console.error('音频播放错误', err);
      this.isPlaying = false;
      callbacks.onError && callbacks.onError(err);
    });
  }

  // 开始录音
  startRecord(options = {}) {
    return new Promise((resolve, reject) => {
      wx.authorize({
        scope: 'scope.record',
        success: () => {
          this.recordTime = 0;
          this.recorderManager.start({
            duration: options.duration || 60000,
            sampleRate: options.sampleRate || 16000,
            numberOfChannels: options.numberOfChannels || 1,
            encodeBitRate: options.encodeBitRate || 96000,
            format: options.format || 'mp3'
          });
          resolve();
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  }

  // 停止录音
  stopRecord() {
    if (this.isRecording) {
      this.recorderManager.stop();
    }
  }

  // 播放音频
  playAudio(audioPath) {
    if (!audioPath || this.isPlaying) return;
    
    this.audioContext.src = audioPath;
    this.audioContext.play();
  }

  // 停止播放
  stopAudio() {
    if (this.isPlaying) {
      this.audioContext.stop();
    }
  }

  // 开始录音计时
  startRecordTimer() {
    this.recordTimer = setInterval(() => {
      this.recordTime++;
    }, 1000);
  }

  // 停止录音计时
  stopRecordTimer() {
    if (this.recordTimer) {
      clearInterval(this.recordTimer);
      this.recordTimer = null;
    }
  }

  // 获取录音时长
  getRecordTime() {
    return this.recordTime;
  }

  // 销毁资源
  destroy() {
    this.stopRecordTimer();
    if (this.audioContext) {
      this.audioContext.destroy();
    }
  }
}

module.exports = AudioManager;